
#include "Service.h"
#include "ServiceBase.h"
#include "Common/Errors.h"
#include "Common/Strings.h"

using namespace std;
using namespace ttg;
using namespace ttg::services;

//---------------
//--- Service ---
//---------------

void Service::makeRegistration()
{
	ServiceBase::getRef()->add(this);
}

Service::Service(const char *name, const char *deps, bool is_updatable)
	:NamedObject(name)
{
	this->is_started = false;
	this->is_updatable = is_updatable;
	if (deps != NULL)
	{
		ttg::strings::StringSplitter sp;
		sp.setSplitter(' ', false);
		sp.setSplitter('\n', false);
		sp.setString(deps);
		dependencies.resize(sp.getCount());
		for (size_t i = 0; i < sp.getCount(); i++)
			dependencies[i] = sp[i];
	}
}

void Service::start(std::vector<Service *> &deps, const char *params)
{
	if (!is_started)
	{
#ifdef TTG_DEBUG
		if (dependencies.size() != deps.size())
			throw Error(Error::FATAL, "Service", "start",
						"There aren't enough parameters");
#endif
		onStarting().notify(true);
		this->startUnSafe(deps, params);
		is_started = true;
		onStart().notify(true);
	}
}

void Service::stop()
{
	if (is_started)
	{
		onStopping().notify(true);
		this->stopUnSafe();
		is_started = false;
		onStop().notify(true);
	}
}

void Service::update(float step)
{
	if (is_updatable && is_started)
		this->updateUnSafe(step);
}
